<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { h, onBeforeMount, onMounted, reactive, ref, watch } from 'vue'
import { queryAllAttachment } from '/@/api/org/file-attachment'
import fileTypeServiceApi from '/@/api/org/bean/file-type'
import filesServiceApi from '/@/api/org/bean/files'
import { downloadFileUrl } from '/@/api/org/file-attachment'
import errImg from "/@/assets/img/file-type/img.svg"

const emit = defineEmits<{
    (e: 'parentid', val: String): void,
    (e: 'breadcrumb', val: Object): void,
    (e: 'isRoot', val: boolean | undefined): void,
    (e: 'syncTableData', val: boolean | undefined): void,
}>()
const addFileInputRef = ref()

const props = defineProps({
    queryParams: {
        type: Object,
        require: true
    },
    height: {
        type: Number,
    }
})
type filesListItem = {
    businessid: string,
    businesstype: string,
    createPerson: string,
    createTime: string,
    delflag: number,
    deptId: [string, number],
    description: string,
    fileName: string,
    filecategory: string,
    filesize: number,
    filetype: string,
    ftype: string,
    icon: string,
    orderNum: 0,
    orgId: string,
    parentid: [number, null],
    projectid: string,
    selected: Boolean,
    state: [null, number, string]
    subOrgId: string,
    uuid: string,
    imgUrl?: Boolean
}
type QueryParams = {
    rows: number,
    page: number,
    projectid: string,
    filecategory: string,
    businessid: string,
    businesstype: string,
    delflag: number,
    isRoot?: boolean | undefined,
    parentid?: string | null | undefined,
}
const attachementPictureRef = ref()
const pictureModeState = reactive({
    addFileName: '新建文件夹',
    filesList: {},
    addNewFileShow: false,
    queryParams: {
        /**分页参数 一页几行 */
        rows: 25,
        /**分页参数 第几页*/
        page: 1,
        /**项目编号 */
        projectid: props.queryParams?.projectid,
        /**分页参数 对应上传compId */
        filecategory: props.queryParams?.filecategory,
        /**业务类型 对应上传 itemType */
        businesstype: props.queryParams?.businesstype,
        /**是否删除 默认给0*/
        delflag: 0,
        /**是否为root目录 有可能存在不同的子文件夹*/
        isRoot: props.queryParams?.isRoot,
        /**如果进入子文件夹需要携带这个参数 */
        parentid: props.queryParams?.parentid,
        /**业务id 对应上传busiId*/
        businessid: props.queryParams?.businessid
    } as QueryParams,
    // 新增文件夹
    addFileInputBlur: (event: Event) => {
        const bean = {
            businessid: pictureModeState.queryParams.businessid,//这个是必填参数 busiId
            businesstype: pictureModeState.queryParams.businesstype,//这个是必填参数 itemType
            parentid: pictureModeState.queryParams.parentid,//如果是根文件夹 为空 有父文件夹为父文件夹uuid
            projectid: pictureModeState.queryParams.projectid,//这个是必填参数 projectid
            typename: pictureModeState.addFileName //这个是输入的文件夹名称
        }
        ElMessageBox({
            title: '新建文件夹',
            message: h('p', null, [
                h('span', null, '您确定要创建名为 '),
                h('span', { style: 'color: teal' }, pictureModeState.addFileName),
                h('span', null, ' 的文件夹吗？ '),
            ]),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            beforeClose: (action: any, instance: { confirmButtonLoading: boolean; confirmButtonText: string }, done: () => void) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true
                    instance.confirmButtonText = 'Loading...'
                    fileTypeServiceApi.saveInsert(bean).then((res) => {
                        emit("syncTableData", true)
                        pictureModeState.addFileName = '新建文件夹'
                    }).catch(err => console.log(err)
                    ).finally(() => {

                        ElMessage({
                            type: 'success',
                            message: '创建完成',
                        })
                        instance.confirmButtonLoading = false
                        pictureModeState.addNewFileShow = false
                    })
                    done()
                } else {
                    pictureModeState.addNewFileShow = false
                    done()
                }
            },
        }).then(() => {

        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '取消该创建',
            })
        })
    },
    // 如果是文件夹 双击
    fileDblclick: (item: any) => {
        if (item.filetype === "folder") {
            // console.log(item)
            /**如果进入子文件夹需要携带这个参数 */
            // console.log("item.uuid", item.uuid)
            pictureModeState.queryParams.parentid = item.uuid
            emit("parentid", item.uuid)
            if (pictureModeState.queryParams.parentid) {
                pictureModeState.queryParams.isRoot = undefined
                emit("isRoot", undefined)
            }
            // 导航条
            emit("breadcrumb", item)
            emit("syncTableData", true)
        } else if (item === 'newFolder') {
            console.log("newFolder")
        }
    },
    // 删除当前文件
    delCurrentFile: (item: filesListItem) => {
        console.log(item.fileName)
        ElMessageBox.confirm(
            `确定永久删除文件：${item.fileName}?`,
            '注意',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
            .then(async () => {
                const bean = { uuid: item.uuid, ftype: item.ftype }
                await filesServiceApi.delFiles([bean]).then((res) => {
                    ElMessage({
                        type: 'success',
                        message: '删除完成',
                    })
                }).catch(err => {
                    console.log(err)
                    ElMessage({
                        type: 'warning',
                        message: '删除失败，请稍后再试',
                    })
                }).finally(() => {
                    emit("syncTableData", true)
                })



            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消删除',
                })
            })
    },
    inputFocus: () => {
        return addFileInputRef.value.focus()
    },
    loadData: (params: any) => {
        return queryAllAttachment({ ...params })
    },
    reloadData: () => {
        pictureModeState.loadData(pictureModeState.queryParams).then(({ data }) => {
            let filesList = data.rows
            total.value = data.total
            filesList.forEach((item: filesListItem, i) => {
                switch (item.filetype) {
                    case "png": {
                        item.imgUrl = true
                        break
                    }
                    case "jpg": {
                        item.imgUrl = true
                        break
                    }
                    case "jpeg": {
                        item.imgUrl = true
                        break
                    }
                    case "xlsx": {
                        filesList[i].icon = '#icon-Excel'
                        break
                    }
                    case "excel": {
                        filesList[i].icon = '#icon-Excel'
                        break
                    }
                    case "doc": {
                        filesList[i].icon = '#icon-Word'
                        break
                    }
                    case "docx": {
                        filesList[i].icon = '#icon-Word'
                        break
                    }
                    case "word": {
                        filesList[i].icon = '#icon-WPS'
                        break
                    }
                    case "pdf": {
                        filesList[i].icon = '#icon-Pdf'
                        break
                    }
                    case "txt": {
                        filesList[i].icon = '#icon-txt'
                        break
                    }

                    case "folder": {
                        filesList[i].icon = '#icon-File'
                        break
                    }
                    case "zip": {
                        filesList[i].icon = '#icon-yasuobao'
                        break
                    }
                    case "rar": {
                        filesList[i].icon = '#icon-yasuobao'
                        break
                    }
                    default: {
                        filesList[i].icon = '#icon-weizhiwenjian'
                    }

                }
            })
            pictureModeState.filesList = filesList
        }).catch((err) => {
            console.error(err)
        })
    }
})
// 分页器
const total = ref(0)
const handleSizeChange = (val: any) => {
    pictureModeState.queryParams.rows = val
    emit("syncTableData", true)
}
const handleCurrentChange = (val: any) => {
    pictureModeState.queryParams.page = val
    emit("syncTableData", true)
}
watch(() => pictureModeState.queryParams.parentid, (val: any) => {
    return emit("parentid", val)
})
const imgErrorHandle = () => {
    document.addEventListener("error", function (e) {
        var elem: any = e.target
        if (elem.tagName.toLowerCase() == "img") {
            elem.src = errImg
            elem.title = "图片链接失效"
        }
    }, true)
}
onBeforeMount(() => {
    //页面图片加载失败时 默认显示统一处理
    imgErrorHandle()
})
onMounted(() => {
    if (props.height) {
        attachementPictureRef.value.style.height = (props.height - 60) + 'px'
    }
})

defineExpose({
    pictureModeState
})
</script>
<template>
    <div class="attachement-picture-container" ref="attachementPictureRef">
        <!-- 新建文件夹 -->
        <div class="file-block" v-show="pictureModeState.addNewFileShow">
            <jxtech-svg-icon
                icon="#icon-tabguanbi"
                :size="24"
                class="file-block-shanchu"
                @click="pictureModeState.addNewFileShow = false"
            ></jxtech-svg-icon>
            <div class="defalut-file-img">
                <jxtech-svg-icon
                    icon="#icon-File"
                    :size="80"
                    @dblclick="pictureModeState.fileDblclick('newFolder')"
                ></jxtech-svg-icon>
            </div>
            <el-input
                v-model="pictureModeState.addFileName"
                @keyup.enter="() => { if (addFileInputRef) { addFileInputRef.blur() } }"
                @blur="pictureModeState.addFileInputBlur"
                ref="addFileInputRef"
            ></el-input>
        </div>
        <!-- 数据返回渲染 -->
        <div
            class="file-block"
            v-for="item: filesListItem in pictureModeState.filesList"
            :key="item.uuid"
            :class="{ 'is-selected': item.selected == true }"
        >
            <jxtech-svg-icon
                icon="#icon-tabguanbi"
                :size="24"
                class="file-block-shanchu"
                @click="pictureModeState.delCurrentFile(item)"
            ></jxtech-svg-icon>

            <el-checkbox v-model="item.selected" class="attachement-picture-checkbox"></el-checkbox>

            <div class="defalut-file-img">
                <img
                    :src="downloadFileUrl + item.uuid"
                    v-if="item.imgUrl"
                    style="width: 100%;height:100px;"
                />
                <!-- <el-image
                    style="width: 100px; height: 100px"
                    :src="downloadFileUrl + item.uuid"
                    :preview-src-list="downloadFileUrl + item.uuid"
                    :append-to-body="true"
                ></el-image>-->
                <jxtech-svg-icon
                    v-else
                    :icon="item.icon"
                    :size="80"
                    @dblclick="pictureModeState.fileDblclick(item)"
                ></jxtech-svg-icon>
            </div>

            <div class="defalut-file-name" :title="item.fileName">{{ item.fileName }}</div>
        </div>
    </div>
    <div class="picture-mode-pagination">
        <el-pagination
            v-model:currentPage="pictureModeState.queryParams.page"
            :page-sizes="[10, 25, 50, 100]"
            :page-size="pictureModeState.queryParams.rows"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        ></el-pagination>
    </div>
</template>
<style lang="scss" scoped>
.is-selected {
    background-color: #ddd;
    .el-checkbox {
        display: inline-block !important;
    }
}

.attachement-picture-container {
    padding: 10px 20px;
    overflow: auto;
    // height: 200px;
    height: calc(100vh - 254px);
    width: 100%;
    .file-block {
        float: left;
        width: 200px;
        height: 140px;
        text-align: center;
        padding: 10px;
        // border: 1px solid #ccc;
        border-radius: 4px;
        transition: all 0.2s;
        flex-shrink: 0;
        margin: 10px 10px;
        flex-wrap: wrap;
        background-color: #f5f5f5;

        &:hover {
            transform: scale(1.04);
            background-color: #ddd;
        }
        .doc-management-title {
            font-size: 18px;
        }
    }
    .attachement-picture-checkbox {
        position: absolute;
        left: 10px;
        top: 10px;
        display: none;
    }
    .file-block {
        position: relative;
        overflow: hidden;
        &:hover {
            .file-block-shanchu {
                top: 0;
                right: 0;
            }
            .attachement-picture-checkbox {
                display: inline-block;
            }
        }
        .file-block-shanchu {
            position: absolute;
            transition: all 0.2s ease-in;
            transform: rotateZ(270deg);
            top: -20px;
            right: -20px;
            cursor: pointer;
        }
        .defalut-file-img {
            width: 180px;
            height: 100px;
        }
        .defalut-file-name {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
        }
        ::v-deep(.el-input) {
            width: 150px;
            font-size: 16px;
            position: relative;
            top: -4px;
        }
        ::v-deep(.el-input__inner) {
            border: none !important;
            height: 30px;
            text-align: center;
            &:focus {
                background-color: rgb(226, 226, 226);
            }
        }
    }
}
.picture-mode-pagination {
    display: flex;
    justify-content: end;
    height: 60px;
    // align-items: center;
    padding-right: 6px;
    padding-top: 5px;
}
</style>